<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\admin\model\User;
use app\common\controller\Backend;
use think\Db;

/**
 * 订单分红结算单
 *
 * @icon fa fa-circle-o
 */
class Orderbonussettlement extends Backend
{

    /**
     * Orderbonussettlement模型对象
     * @var \app\admin\model\Orderbonussettlement
     */
    protected $model = null;

    /**
     * Orderbonussettlementitem模型对象
     * @var \app\admin\model\Orderbonussettlementitem
     */
    protected $itemModel = null;

    /**
     * Orderbonusitem模型对象
     * @var \app\admin\model\Orderbonusitem
     */
    protected $bonusItemModel = null;

    /**
     * User模型对象
     * @var \app\admin\model\User
     */
    protected $userModel = null;

    /**
     * User模型对象
     * @var \app\admin\model\Agentbonusraterecord
     */
    protected $bonusRecordModel = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Orderbonussettlement;
        $this->itemModel = new \app\admin\model\Orderbonussettlementitem;
        $this->bonusItemModel = new \app\admin\model\Orderbonusitem;
        $this->userModel = new \app\admin\model\User;
        $this->bonusRecordModel = new \app\admin\model\Agentbonusraterecord;
    }

    /**
     * 编辑
     * @param $ids
     * @return string|void
     */
    public function edit($ids = null)
    {
        // 查询数据
        $row = $this->model->find($ids);

        // 更新数据
        if ($this->request->isPost()) {

            // 检查数据
            if ($row['status'] == 2) {
                $this->error('单据已结算,禁止修改');
            }

            // 请求参数
            $param = $this->request->param();

            // 提取参数
            $param_row = $param['row'] ?? [];
            if (!$param_row) {
                $this->error('请求参数不得为空');
            }
            $time = time();
            $param_row['settlement_time'] = $param_row['settlement_time'] ? strtotime($param_row['settlement_time']) : $time;

            // 组装数据
            $saveData = [
                'status' => $param_row['status'],
                'real_amount' => $param_row['real_amount'],
                'remark' => $param_row['remark'],
                'settlement_time' => $param_row['settlement_time'],
                'update_time' => $time,
            ];

            // 更新主单数据
            Db::startTrans();
            $isUpdate1 = $this->model->where(['id' => $ids])->update($saveData);
            if ($isUpdate1 === false) {
                $this->error('更新结算单失败');
            }

            // 如果是已结算的操作
            if ($saveData['status'] == 2) {

                // 更新分红明细,标记已结算
                $where = ['order_id' => $ids];
                $all_bonus_item_id = $this->itemModel->where($where)->column('bonus_item_id');
                if (!$all_bonus_item_id) {
                    $this->error('未找到分红明细记录');
                }

                $where = ['id' => ['in', $all_bonus_item_id]];
                $saveItemData = [
                    'is_settlement' => 1,
                    'update_time' => $time,
                ];
                $isUpdate2 = $this->bonusItemModel->where($where)->update($saveItemData);
                if ($isUpdate2 === false) {
                    $this->error('更新分红明细失败');
                }

                // 用户分销比例调整
                $bonusItemList = $this->bonusItemModel->where($where)->select();
                foreach ($bonusItemList as $bonusItem) {
                    // 提取参数
                    $change_val = 1;
                    $relation_level = $bonusItem['relation_level'];

                    // 查询用户信息
                    $userInfo = $this->userModel->getUserByUid($row['agent_id'], 'bonus_rate_one,bonus_rate_two');
                    if (!$userInfo) {
                        $this->error('未找到代理信息');
                    }

                    // 检查用户分红比例是否达到最大值
                    if ($relation_level == 1 && $userInfo['bonus_rate_one'] >= 50) {
                        continue;
                    }
                    if ($relation_level == 2 && $userInfo['bonus_rate_two'] >= 30) {
                        continue;
                    }

                    // 更新用户分销比例
                    $rate_key = $relation_level == 1 ? 'bonus_rate_one' : 'bonus_rate_two';
                    $old_rate = $userInfo[$rate_key];
                    $new_rate = $old_rate + $change_val;
                    $whereUser = [
                        'id' => $row['agent_id'],
                        $rate_key => $old_rate,
                    ];
                    $saveUserData = [
                        $rate_key => $new_rate
                    ];
                    $isUpdate = $this->userModel->where($whereUser)->update($saveUserData);
                    if (!$isUpdate) {
                        $this->error('更新用户分销比例失败');
                    }

                    // 保存分销比例日志
                    $auth = Auth::instance();
                    $admin_id = $auth->isLogin() ? $auth->id : 0;
                    $time = time();
                    $record = [
                        'uid' => $row['agent_id'],
                        'old_rate' => $old_rate,
                        'new_rate' => $new_rate,
                        'rate_type' => $relation_level,
                        'change_val' => $change_val,
                        'relation_order_id' => $bonusItem['id'],
                        'relation_order_type' => 1,
                        'admin_uid' => $admin_id,
                        'create_time' => $time,
                        'update_time' => $time,
                    ];
                    $isInsert = $this->bonusRecordModel->insert($record);
                    if (!$isInsert) {
                        $this->error('保存分销日志失败');
                    }
                }
            }
            Db::commit();
            $this->success();
        }

        $this->assign('row', $row);
        return $this->view->fetch();
    }


}
